# @FileName  : main.py
# @Time      : 2024/8/12 11:00
# @Author    : LuZhaoHui
# @Software  : PyCharm

import pdf2docx
import PyPDF2
import pdfplumber
import pptx
from pptx.util import Inches
import openpyxl
import pdf2image
from tool import *

CURDIR = "d:/data/file"


def getPdfPageNums(file):
    with open(file, 'rb') as f:
        pdf = PyPDF2.PdfReader(f)
        return len(pdf.pages)
    return 0


def pdf2word(pdfName):
    print("pdf2word %s" % (pdfName))
    pdfFile = pathJoin(CURDIR, pdfName)

    docxFile = pathJoin(CURDIR, pdfName.split('.')[0]) + ".docx"

    cv = pdf2docx.Converter(pdfFile)
    # cv.load_pages()
    # cv.parse_document()
    # cv.parse_pages()
    # cv.make_docx(docxFile)

    cv.convert(docxFile)
    cv.close()


def pdf2excel(pdfName):
    print("pdf2excel %s" % (pdfName))
    pdfFile = pathJoin(CURDIR, pdfName)
    excelFile = pathJoin(CURDIR, pdfName.split('.')[0]) + ".xlsx"
    # 创建表
    wb = openpyxl.Workbook()
    ws = wb.active
    # 加载PDF
    with pdfplumber.open(pdfFile) as pdf:
        table = pdf.pages[0].extract_tables()

    for row in table:
        ws.append(row)

    wb.save(excelFile)


def pdf2ppt(pdfName):
    print("pdf2excel %s" % (pdfName))
    pdfFile = pathJoin(CURDIR, pdfName)
    bname = pdfName.split('.')[0]
    pptFile = pathJoin(CURDIR, bname) + ".pptx"

    images = pdf2image.convert_from_path(pdfFile, dpi=300)
    # 创建ppt
    ppt = pptx.Presentation()

    for idx, image in enumerate(images):
        slide = ppt.slides.add_slide(ppt.slide_layouts[0])
        image_name = "%s%d.jpg" % (pathJoin(CURDIR, bname), idx)
        image.save(image_name, 'JPEG')
        shapes = slide.shapes
        pic = shapes.insert_picture(image_name, Inches(0), Inches(0), Inches(8), Inches(6))

    ppt.save(pptFile)


if __name__ == '__main__':
    print('文件转换')

    # pdf2word("test2.pdf")
    # pdf2excel("test1.pdf")
    pdf2ppt("test2.pdf")

# app = QApplication(sys.argv)
#
# main = ocrRun()
# main.show()
#
# sys.exit(app.exec_())
